package com.thinkverse.common.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

/**
 * 密码加密配置
 */
@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class SecurityConfig {

    /**
     * 注册 PasswordEncoder Bean
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize
                        // 允许匿名访问文档接口
                        .requestMatchers(
                                "/swagger-ui.html",
                                "/doc.html",
                                "/v3/api-docs/**",
                                "/webjars/**",
                                "/auth/login", // 如果你有自定义登录接口，也需要允许匿名访问
                                "/auth/register/**"
                        ).permitAll()
                        // 其他所有请求需要认证
                        .anyRequest().authenticated()
                )
                .formLogin(form -> form
                        // 可选：自定义登录页面路径（如果需要）
                        // .loginPage("/auth/login")
                        // 登录成功后的默认跳转路径
                        .defaultSuccessUrl("/", true)
                )
                .csrf(csrf -> csrf.disable()); // 测试阶段禁用 CSRF

        return http.build();
    }

}
